<template>
  <div class="job-list-container" style="padding: 20px">
    <!-- 搜索条件区域 -->
    <el-card shadow="hover" style="margin-bottom: 20px" class="gradient-bg-card">
      <el-form :model="queryParams" label-width="100px" label-position="left" @submit.prevent="handleQuery">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公司名称">
              <el-input
                v-model="queryParams.companyName"
                placeholder="请输入公司名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位名称">
              <el-input
                v-model="queryParams.jobName"
                placeholder="请输入岗位名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作地点">
              <el-input
                v-model="queryParams.workLocation"
                placeholder="请输入工作地点（全国匹配所有）"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公司类型">
              <el-select
                v-model="queryParams.companyTypeId"
                placeholder="请选择公司类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in companyTypeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="招聘类型">
              <el-select
                v-model="queryParams.jobTypeId"
                placeholder="请选择招聘类型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in jobTypeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="最低学历">
              <el-select
                v-model="queryParams.educationalBackgroundId"
                placeholder="请选择最低学历"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in educationOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="招聘对象">
              <el-select
                v-model="queryParams.candidateId"
                placeholder="请选择招聘对象"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in candidateOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="投递状态" v-if="!isAdmin">
              <el-select
                v-model="queryParams.statusId"
                placeholder="请选择投递状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="批量操作" v-else>
              <el-button-group>
                <el-button type="success" @click="handleBatchAdd">批量添加</el-button>
                <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
              </el-button-group>
            </el-form-item>
          </el-col>

          <el-col :span="8" style="display: flex; align-items: flex-end">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 结果表格 -->
    <el-table
      :data="jobList"
      border
      stripe
      style="width: 100%; margin-bottom: 20px"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <!-- 添加多选列 -->
      <el-table-column type="selection" width="30" v-if="isAdmin" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="companyName" label="公司名称" width="120" />
      <el-table-column label="公司类型" width="81">
        <template #default="scope">
          {{ formatCompanyType(scope.row.companyTypeId) }}
        </template>
      </el-table-column>
      <el-table-column prop="companyIndustry" label="所属行业" width="150" />
      <el-table-column prop="workLocation" label="工作地点" width="120" />
      <el-table-column label="招聘类型" width="81">
        <template #default="scope">
          {{ formatJobType(scope.row.jobTypeId) }}
        </template>
      </el-table-column>
      <el-table-column label="招聘对象" width="81">
        <template #default="scope">
          {{ formatCandidateType(scope.row.candidateId) }}
        </template>
      </el-table-column>
      <el-table-column label="最低学历" width="81">
        <template #default="scope">
          {{ formatEducation(scope.row.educationalBackgroundId) }}
        </template>
      </el-table-column>
      <el-table-column prop="jobName" label="岗位名称" min-width="150" />
      <el-table-column prop="jobNum" label="岗位数" width="67" align="center" />
      <el-table-column label="投递状态" width="120" v-if="!isAdmin">
  <template #default="scope">
    <!-- 点击区域 -->
    <div
      v-if="!scope.row.isEditing"
      style="cursor: pointer; padding: 4px;"
      @click="openStatusSelect(scope.row)"
    >
      <el-tag :type="statusTagType(scope.row.statusId)" size="small">
        {{ formatStatus(scope.row.statusId) }}
      </el-tag>
    </div>

    <!-- 编辑状态：内联 el-select -->
    <el-select
      v-else
      v-model="scope.row.statusId"
      style="width: 100%"
      size="small"
      filterable
      popper-append-to-body="false"
      @change="onStatusChange(scope.row)"
      @blur="() => { scope.row.isEditing = false; editingRow.value = null }"
    >
      <el-option
        v-for="item in statusOptions"
        :key="item.id"
        :label="item.value"
        :value="item.id"
      />
    </el-select>
  </template>
      </el-table-column>
      <el-table-column label="操作岗位" min-width="120" v-else>
        <template #default="scope">
          <el-button type="warning" size="small" @click="addJob(scope.row)">
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteSingle(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="97" />
      <el-table-column label="截止时间" width="97">
        <template #default="scope">
          {{ scope.row.dateline || '招满为止' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" link @click="deliverJob(scope.row)">
            投递
          </el-button>
          <el-button size="small" type="success" link @click="viewNotice(scope.row)">
            公告
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />


    <!-- 添加/修改岗位弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :width="showParsedJobs ? '100%' : '600px'"
      @close="resetForm"
    >
      <el-form
        v-if="!showParsedJobs"
        :model="jobForm"
        label-width="100px"
        ref="jobFormRef"
        status-icon
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="jobForm.companyName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司类型" prop="companyTypeId">
              <el-select v-model="jobForm.companyTypeId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in companyTypeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        
          <el-col :span="12">
            <el-form-item label="所属行业">
              <el-input v-model="jobForm.companyIndustry" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作地点" prop="workLocation">
              <el-input v-model="jobForm.workLocation" placeholder="请输入" />
            </el-form-item>
          </el-col>
        
          <el-col :span="12">
            <el-form-item label="招聘类型" prop="jobTypeId">
              <el-select v-model="jobForm.jobTypeId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in jobTypeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="招聘对象" prop="candidateId">
              <el-select v-model="jobForm.candidateId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in candidateOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        
          <el-col :span="12">
            <el-form-item label="最低学历" prop="educationalBackgroundId">
              <el-select v-model="jobForm.educationalBackgroundId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in educationOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位数量">
              <el-input-number v-model="jobForm.jobNum" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="更新时间">
              <el-date-picker
                v-model="jobForm.updateTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间">
              <el-date-picker
                v-model="jobForm.dateline"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期（可为空）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="岗位名称" prop="jobName">
              <el-input v-model="jobForm.jobName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        
          <el-col :span="22">
            <el-form-item label="投递链接">
              <el-input v-model="jobForm.jobLink" placeholder="请输入投递链接" />
            </el-form-item>
          </el-col>
          <el-col :span="2" v-if="jobForm.jobLink" >
            <el-link :href="jobForm.jobLink" target="_blank" type="primary">
              预览
            </el-link>
          </el-col>
          <el-col :span="22">
            <el-form-item label="公告链接">
              <el-input v-model="jobForm.noticeLink" placeholder="请输入公告链接" />
            </el-form-item>
          </el-col>
          <el-col :span="2" v-if="jobForm.noticeLink" >
            <el-link :href="jobForm.noticeLink" target="_blank" type="primary">
              预览
            </el-link>
          </el-col>
        </el-row>
      </el-form>
    
      <div v-if="showParsedJobs" style="margin-top: 10px;">
        <h4 style="color: #1890ff; margin-bottom: 10px;">Excel 导入岗位列表</h4>
        <el-table :data="parsedJobsList" size="small" border style="width: 100%">
          <el-table-column type="index" label="序号" width="41" />
          <el-table-column prop="companyName" label="公司名称" width="79">
            <template #default="{ row }">
              <el-input v-model="row.companyName" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="companyTypeId" label="公司类型" width="99">
            <template #default="{ row }">
              <el-select v-model="row.companyTypeId" size="small" style="width: 100%">
                <el-option
                  v-for="item in companyTypeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="companyIndustry" label="所属行业" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.companyIndustry" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="workLocation" label="工作地点" width="79">
            <template #default="{ row }">
              <el-input v-model="row.workLocation" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="jobTypeId" label="招聘类型" width="111">
            <template #default="{ row }">
              <el-select v-model="row.jobTypeId" size="small" style="width: 100%">
                <el-option
                  v-for="item in allJobTypeOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="candidateId" label="招聘对象" width="78">
            <template #default="{ row }">
              <el-select v-model="row.candidateId" size="small" style="width: 100%">
                <el-option
                  v-for="item in candidateOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="educationalBackgroundId" label="最低学历" width="79">
            <template #default="{ row }">
              <el-select v-model="row.educationalBackgroundId" size="small" style="width: 100%">
                <el-option
                  v-for="item in educationOptions"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="jobName" label="岗位名称" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.jobName" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="jobNum" label="岗位数" width="92">
            <template #default="{ row }">
              <el-input-number v-model="row.jobNum" :min="1" size="small" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="112">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.updateTime"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                size="small"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column prop="dateline" label="截止时间" width="112">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.dateline"
                type="date"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                placeholder="可为空"
                size="small"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column prop="jobLink" label="投递链接" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.jobLink" size="small" />
              <el-link :href="row.jobLink" target="_blank" style="margin-left: 5px;">
                预览
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="noticeLink" label="公告链接" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.noticeLink" size="small" />
              <el-link :href="row.noticeLink" target="_blank" style="margin-left: 5px;">
                预览
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="{ $index }">
              <el-button type="danger" size="small" @click="parsedJobsList.splice($index, 1)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px; color: #999; font-size: 13px;">
          共 {{ parsedJobsList.length }} 个岗位，可编辑后提交。
        </div>
      </div>
      <template #footer>
        <div
          v-if="dialogTitle === '批量添加岗位'"
          style="margin-bottom: 10px; display: flex; align-items: center; gap: 10px;"
        >
          <!-- 上传 Excel -->
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleUpload"
            accept=".xlsx,.xls"
            style="display: inline-flex; align-items: center; margin: 0; padding: 0;"
          >
            <el-button size="small" type="primary" plain>上传 Excel</el-button>
          </el-upload>
        
          <!-- 下载模板 -->
          <el-button size="small" type="info" plain @click="downloadTemplate">
            下载模板
          </el-button>
        
          <!-- 清空 -->
          <el-button
            v-if="parsedJobsList.length"
            size="small"
            type="warning"
            plain
            @click="clearParsedJobs"
          >
            清空
          </el-button>
        </div>
      
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'

// 假设这些 API 已定义，返回 { code: 1, data: [...] }
import {
  getJobsApi,
  setStatusApi,
  getCompanyTypeApi,
  getSchoolJobTypeApi,
  getJobTypeApi,
  getCandidateTypeApi,
  getEducationalBackgroundTypeApi,
  getStatusTypeApi,

  batchAddJobsApi,
  getJobByIdApi,
  updateJobApi,
  batchDeleteJobsApi,
  downloadTemplateApi,
  excelApi
} from '../api/Job'

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单数据模型
const jobForm = reactive({
  id: null,
  companyName: '',
  companyTypeId: null,
  companyIndustry: '',
  workLocation: '',
  jobTypeId: null,
  candidateId: null,
  educationalBackgroundId: null,
  jobName: '',
  jobNum: 1,
  updateTime: '',
  dateline: '', // 截止时间
  jobLink: '',
  noticeLink: '',
  type: 'school' // 固定为校招
})

// 查询参数
const queryParams = reactive({
  companyName: '',
  companyTypeId: null,
  workLocation: '',
  jobTypeId: null,
  candidateId: null,
  educationalBackgroundId: null,
  jobName: '',
  statusId: null,
  type: 'school',
  page: 1,
  pageSize: 5
})

// 岗位列表 & 总数
const jobList = ref([])
const total = ref(0)
const loading = ref(false)
const isAdmin = ref(false)

const selectedRows = ref([])

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const isAdminFct = () => {
  isAdmin.value = localStorage.getItem('userId') === '1'? true : false
}


// 当前正在编辑状态的行
const editingRow = ref(null)

// 下拉选项
const companyTypeOptions = ref([])
const jobTypeOptions = ref([])
const allJobTypeOptions = ref([])
const educationOptions = ref([])
const candidateOptions = ref([])
const statusOptions = ref([])
// 存储从 Excel 解析出的岗位列表（用于表格展示 + 提交）
const parsedJobsList = ref([])

// 控制是否显示“从 Excel 导入”的表格
const showParsedJobs = ref(false)

const downloadTemplate = () => {
  downloadTemplateApi().then(res => {
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '岗位导入模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  }).catch(err => {
    console.error('下载失败:', err)
  })
}

// Date/string -> 后端需要的 yyyy-MM-dd 字符串（或空字符串）
const formatDateForBackend = (val) => {
  if (!val) return ''
  if (val instanceof Date && !isNaN(val.getTime())) {
    return val.toISOString().split('T')[0]
  }
  // 如果是字符串，尝试解析再格式化
  const d = new Date(val)
  if (!isNaN(d.getTime())) return d.toISOString().split('T')[0]
  return String(val)
}

// 每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.page = 1 // 改变条数后回到第一页
  fetchJobList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchJobList()
}


// 格式化方法
const formatEducation = (id) => {
  const item = educationOptions.value.find(opt => opt.id === id)
  return item ? item.value : '未知'
}

const formatCompanyType = (id) => {
  const item = companyTypeOptions.value.find(opt => opt.id === id)
  return item ? item.value : '未知'
}

const formatJobType = (id) => {
  const item = jobTypeOptions.value.find(opt => opt.id === id)
  return item ? item.value : '未知'
}

const formatCandidateType = (id) => {
  const item = candidateOptions.value.find(opt => opt.id === id)
  return item ? item.value : '未知'
}

const formatStatus = (id) => {
  const item = statusOptions.value.find(opt => opt.id === id)
  return item ? item.value : '未投递'
}

const statusTagType = (id) => {
  if (id === 16) return 'info'
  if (id === 17 || id === 18 || id === 19 || id === 22) return 'warning'
  if (id === 21) return 'success'
  if (id === 20) return 'danger'
  return 'info'
}

// 打开状态选择
const openStatusSelect = (row) => {
  // 关闭上一个
  if (editingRow.value) {
    editingRow.value.isEditing = false
  }
  // 打开当前
  row.isEditing = true
  editingRow.value = row
}

// 工具函数：Excel 序列号转 YYYY-MM-DD
const formatDateExcelDate = (excelDate) => {
  if (!excelDate) return ''
  const baseDate = new Date(1899, 11, 30) // Excel 日期基准
  const date = new Date(baseDate.getTime() + excelDate * 24 * 60 * 60 * 1000)
  return date.toISOString().split('T')[0] // 返回 'YYYY-MM-DD'
}

const handleUpload = async (uploadFile) => {
  getType()//获取所有招聘类型
  const file = uploadFile.raw // 获取原生 File 对象

  const formData = new FormData()
  formData.append('file', file)

  try {
    // 调用后端接口解析 Excel
    const res = await excelApi(formData)

    if (res.code === 1 && Array.isArray(res.data)) {
      // 将后端解析的数据映射为前端需要的格式
      const mappedData = res.data.map(row => ({
        companyName: row.companyName || jobForm.companyName,
        companyTypeId: row.companyTypeId || jobForm.companyTypeId,
        companyIndustry: row.companyIndustry || jobForm.companyIndustry,
        workLocation: row.workLocation || jobForm.workLocation,
        jobTypeId: row.jobTypeId || jobForm.jobTypeId,
        candidateId: row.candidateId || jobForm.candidateId,
        educationalBackgroundId: row.educationalBackgroundId || jobForm.educationalBackgroundId,
        jobName: row.jobName,
        jobNum: parseInt(row.jobNum) || 1,
        updateTime: normalizeDate(row.updateTime),
        dateline: normalizeDate(row.dateline),
        jobLink: row.jobLink || jobForm.jobLink,
        noticeLink: row.noticeLink || jobForm.noticeLink,
        type: 'school'
      })).filter(item => item.jobName)

      if (mappedData.length === 0) {
        ElMessage.warning('Excel 中无有效岗位数据')
        return
      }

      parsedJobsList.value = mappedData
      showParsedJobs.value = true
      ElMessage.success(`解析成功，共 ${mappedData.length} 个岗位`)
    } else {
      ElMessage.error(res.message || '解析失败，数据格式异常')
    }
  } catch (error) {
    console.error('Excel 解析请求失败:', error)
    ElMessage.error('文件上传或解析失败，请检查网络或文件格式')
  }
}

// 状态改变时提交
const onStatusChange = async (row) => {
  try {
    const res = await setStatusApi(row.id, row.statusId)
    if (res.code === 1) {
      ElMessage.success('状态更新成功')
      row.isEditing = false
      editingRow.value = null
    } else {
      ElMessage.error(res.message || '更新失败')
      // 可选：恢复原状态（需记录旧值）
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络')
    console.error(error)
  }
}

const clearParsedJobs = () => {
  parsedJobsList.value = []
  showParsedJobs.value = false
}

// 请求岗位列表
const fetchJobList = async () => {
  loading.value = true
  try {
    const res = await getJobsApi(queryParams)
    if (res.code === 1) {
      const list = res.data.rows || []
      jobList.value = list.map(row => ({
        ...row,
        isEditing: false // 初始化编辑状态
      }))
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络')
  } finally {
    loading.value = false
  }
}

// 查询与重置
const handleQuery = () => {
  queryParams.page = 1
  fetchJobList()
}

const resetQuery = () => {
  queryParams.companyName = ''
  queryParams.companyTypeId = null
  queryParams.workLocation = ''
  queryParams.jobTypeId = null
  queryParams.candidateId = null
  queryParams.educationalBackgroundId = null
  queryParams.jobName = ''
  queryParams.statusId = null
  queryParams.page = 1
  queryParams.pageSize = 5
  fetchJobList()
}

// 查看公告
const viewNotice = (row) => {
  if (row.noticeLink) {
    window.open(row.noticeLink, '_blank')
  } else {
    ElMessage.warning('暂无公告链接')
  }
}

// 投递岗位
const deliverJob = (row) => {
  if (row.jobLink) {
    window.open(row.jobLink, '_blank')
  } else {
    ElMessage.warning('投递链接未提供')
  }
}

// 获取字典数据
const getCompanyType = async () => {
  const res = await getCompanyTypeApi()
  if (res.code === 1) companyTypeOptions.value = res.data
}

const deleteSingle = (row) => {
  ElMessageBox.confirm(`确定要删除${row.companyName}的岗位吗？`, '警告', {
    type: 'warning'
  }).then(async () => {
      const res = await batchDeleteJobsApi([row.id])
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchJobList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
  })
}

const getSchoolJobType = async () => {
  const res = await getSchoolJobTypeApi()
  if (res.code === 1) jobTypeOptions.value = res.data
}

const getType = async () => {
  const res = await getJobTypeApi()
  if (res.code === 1) allJobTypeOptions.value = res.data
}

const getEducationalBackgroundType = async () => {
  const res = await getEducationalBackgroundTypeApi()
  if (res.code === 1) educationOptions.value = res.data
}

const getCandidateType = async () => {
  const res = await getCandidateTypeApi()
  if (res.code === 1) candidateOptions.value = res.data
}

const getStatusType = async () => {
  const res = await getStatusTypeApi()
  if (res.code === 1) statusOptions.value = res.data
}

// 批量添加
const handleBatchAdd = () => {
  dialogTitle.value = '批量添加岗位'
  // 使用 Object.assign 赋值默认值，避免直接引用导致污染
  Object.assign(jobForm, {
    id: null,
    companyName: '',
    companyTypeId: null,
    companyIndustry: '',
    workLocation: '',
    jobTypeId: null,
    candidateId: null,
    educationalBackgroundId: null,
    jobName: '',
    jobNum: 1,
    updateTime: '',
    dateline: '',
    jobLink: '',
    noticeLink: '',
    type: 'school'
  })

  // 不显示 Excel 表格
  showParsedJobs.value = false
  parsedJobsList.value = []

  dialogVisible.value = true
}

// 修改岗位
const addJob = async (row) => {
  dialogTitle.value = '修改岗位'
  dialogVisible.value = true
  try {
    const res = await getJobByIdApi(row.id)
    if (res.code === 1) {
      const data = res.data || {}
      Object.assign(jobForm, {
        ...data,
        updateTime: data.updateTime || '',
        dateline: data.dateline || ''
      })
    } else {
      ElMessage.error(res.message || '获取岗位信息失败')
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络')
  }
}



// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的岗位')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个岗位吗？`,
    '警告',
    { type: 'warning' }
  ).then(async () => {
    const ids = selectedRows.value.map(row => row.id)
    try {
      const res = await batchDeleteJobsApi(ids)
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchJobList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除请求失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const jobFormRef = ref(null)

const submitForm = () => {
  // 如果有导入的岗位列表，则走批量添加
  if (showParsedJobs.value && parsedJobsList.value.length > 0) {
    // 格式化 parsedJobsList 的日期字段
    const payload = parsedJobsList.value.map(row => ({
      ...row,
      updateTime: formatDateForBackend(row.updateTime),
      dateline: formatDateForBackend(row.dateline)
    }))

    batchAddJobsApi(payload)
      .then(res => {
        if (res.code === 1) {
          ElMessage.success(`成功添加 ${parsedJobsList.value.length} 个岗位`)
          dialogVisible.value = false
          fetchJobList()
        } else {
          ElMessage.error(res.message || '批量添加失败')
        }
      })
      .catch(err => {
        ElMessage.error('请求失败，请检查网络')
        console.error(err)
      })
      .finally(() => {
        clearParsedJobs()
      })
    return
  }

  // 单个新增/修改
  const isEdit = jobForm.id !== null
  const postData = { ...jobForm }

  // 把日期转成 yyyy-MM-dd
  postData.updateTime = formatDateForBackend(postData.updateTime)
  postData.dateline = formatDateForBackend(postData.dateline)

  if (!isEdit) delete postData.id

  const apiCall = isEdit ? updateJobApi(postData) : batchAddJobsApi([postData])
  apiCall
    .then(res => {
      if (res.code === 1) {
        ElMessage.success(isEdit ? '修改成功' : '新增成功')
        dialogVisible.value = false
        fetchJobList()
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    })
    .catch(() => {
      ElMessage.error('网络请求失败')
    })
}
// 统一把后端返回的时间转成字符串 yyyy-MM-dd
const normalizeDate = (val) => {
  if (!val) return ''
  if (val instanceof Date) {
    return val.toISOString().split('T')[0]
  }
  // 如果本身就是 "2025-09-16" 这种，直接返回
  if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) {
    return val
  }
  const d = new Date(val)
  return isNaN(d.getTime()) ? '' : d.toISOString().split('T')[0]
}


// 重置表单
const resetForm = () => {
  jobFormRef.value?.resetFields()
}

// 页面初始化
onMounted(async () => {
  await Promise.all([
    getCompanyType(),
    getSchoolJobType(),
    getEducationalBackgroundType(),
    getCandidateType(),
    getStatusType(),
    isAdminFct(),
  ])
  fetchJobList()
})
</script>

<style scoped>
.job-list-container {
  max-width: 1600px;
  margin: 0 auto;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

/* 动态渐变背景卡片 */
.gradient-bg-card {
  --bg-direction: 45deg;
  --color-stop1: #2bc0e4;
  --color-stop2: #eaecc6;
  --color-stop3: #ffffff;
  background: linear-gradient(
    var(--bg-direction),
    var(--color-stop1),
    var(--color-stop2),
    var(--color-stop3),
    var(--color-stop2),
    var(--color-stop1)
  );
  background-size: 400% 400%;
  animation: gradientShift 60s ease infinite;
  border-radius: 12px;
  overflow: hidden;
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>